<?php

namespace App\Http\Controllers\Wechat\User;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Repos\UserGroupbuyRepo;
use App\Repos\ProductRepo;
use App\Http\Requests\Api\UserGroupbuyRequest;
use Carbon\Carbon;
use Log;

class UserGroupbuyController extends Controller
{
     public function index(CartRequest $request)
    {
    
    	$rs['status'] = false;
    	$where['user_id'] = $request->user_id;
    	$list = UserGroupbuyRepo::getPages($where,$num=10);
    	if($list) {
    		$rs['status'] = true;
    		$rs['data'] = $list;
    		return response()->json($rs);
    	}
    	return response()->json($rs);
    }

    // 发起拼团
    public function create(UserGroupbuyRequest $request)
    {
        $rs['status'] = false;
        $data = $request->pure();

        // 刚开始状态时0 ，提交订单之后改为1
        $data['status'] = 0;
       
        
        $flag = UserGroupbuyRepo::create($data);
        if($flag['status']==true) {
            $rs['status'] = true;
            return response()->json($rs);
        }
        $rs['msg'] = $flag['msg'];
        $rs['data']['group_code'] = array_get($flag,'data.group_code');
        
        return response()->json($rs);
    }  

    public function show(UserGroupbuyRequest $request)
    {
        $rs['status'] = false;
       
        $data = $request->pure();
        $where['code']    = $data['group_code'];
        $where['user_id'] = $data['group_user_id'];
        $where['status'] = 1;
        $data = UserGroupbuyRepo::find($where);
        if(!$data) {
            $rs['msg'] = '抱歉，拼购活动已经结束';
            return response()->json($rs);
        }

        // 判断商品有没有下线       
        $pg = ProductRepo::group($data->product_id);
        if(!$pg) {  
            $rs['msg'] = '抱歉，拼购商品已下架';          
            return response()->json($rs);
        }


        if($data) {
            $rs['data'] = $data;
            $rs['data']['product'] = ProductRepo::find(['id'=>$data['product_id']]);
        }
        $rs['status'] = true;
        return response()->json($rs);
    }
}
